<template>
  <div v-if="!item.hidden">
    <template
      v-if="hasOneShowingChild(item.children,item) && (!onlyOneChild.children||onlyOneChild.noShowingChildren)&&!item.alwaysShow"
    >
      <app-link v-if="onlyOneChild.children && onlyOneChild.children.length === 0" :to="item.path">
        <el-menu-item
          :index="resolvePath(onlyOneChild.path).length>0?resolvePath(onlyOneChild.path):item.id"
          :class="{'submenu-title-noDropdown':!isNest}"
          @click="handleClick(item)"
        >
          <item
            :icon="onlyOneChild.meta && onlyOneChild.meta.icon||(item.meta&&item.meta.icon)"
            :title="onlyOneChild.label"
          />
        </el-menu-item>
      </app-link>
    </template>

    <el-submenu v-else ref="subMenu" :index="resolvePath(item.path)" popper-append-to-body>
      <template slot="title">
        <item
          v-if="item.children && item.children.length > 0"
          :icon="item.meta && item.meta.icon"
          :title="item.label"
        />
      </template>
      <sidebar-item
        v-for="child in item.children"
        :key="child.path"
        :is-nest="true"
        :item="child"
        class="nest-menu"
        :base-path="resolvePath(child.path)"
        @menuClick="cMenuClick"
      />
    </el-submenu>
  </div>
</template>

<script>
import path from "path";
import { isExternal } from "@/util/validate";
import Item from "./item";
import AppLink from "./Link";

export default {
  name: "SidebarItem",
  components: { Item, AppLink },
  props: {
    // route object
    item: {
      type: Object,
      required: true
    },
    isNest: {
      type: Boolean,
      default: false
    },
    basePath: {
      type: String,
      default: ""
    }
  },
  data () {
    // TODO: refactor with render function
    this.onlyOneChild = null;
    return {};
  },
  methods: {
    handleClick (item) {
      this.$emit("menuClick", item);
    },
    cMenuClick (item) {
      this.$emit("menuClick", item);
    },
    hasOneShowingChild (children = [], parent) {
      const showingChildren = children.filter(item => {
        if (item.hidden) {
          return false;
        } else {
          this.onlyOneChild = item;
          return true;
        }
      });

      if (showingChildren.length === 1) {
        return true;
      }

      if (showingChildren.length === 0) {
        this.onlyOneChild = { ...parent, path: "", noShowingChildren: true };
        return true;
      }

      return false;
    },
    resolvePath (routePath) {

      let basePath = "";
      if (!routePath || routePath === null) {
        routePath = "/";
      }
      if (!this.basePath || this.basePath === null) {
        basePath = "/";
      } else {
        basePath = this.basePath;
      }
      if (isExternal(routePath)) {
        return routePath;
      }
      if (isExternal(basePath)) {
        return basePath;
      }
      return path.resolve(basePath, routePath);
    }
  }
};
</script>
